<?php

namespace backend\modules\media\controllers;

use Yii;
use yii\web\Controller;
use yii\bootstrap\Html;
use yii\helpers\FileHelper;
use common\components\Helper;
use yii\web\UploadedFile;
use backend\models\UploadForm;

/**
 * Default controller for the `media` module
 */
class DefaultController extends Controller
{
    protected $upload;

    /**
     * {@inheritDoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => \yii\filters\VerbFilter::class,
                'actions' => [
                    'delete' => ['post'],
                    'create' => ['post'],
                    'upload' => ['post']
                ]
            ]
        ];
    }

    public function init()
    {
        $this->upload = new UploadForm(['exts' => 'jpg, jpeg, png, gif, svg, zip, rar']);
    }

    /**
     * Renders the index view for the module
     * @param string $folder
     * @return string
     */
    public function actionIndex($folder = '')
    {
        Helper::addEntry(Yii::t('mod_media', 'FOLDERS'));
        $mediaRootPath = Yii::getAlias($this->module->mediaPath);

        $allFolders = FileHelper::findDirectories($mediaRootPath);
        sort($allFolders);
        foreach ($allFolders as $absolute) {
            $relativeFolder = substr($absolute, strlen($mediaRootPath));
            $level = count(explode('/', $relativeFolder)) - 2;
            $prefix = str_repeat(Html::tag('i', '&ensp;', ['class' => 'subfolder']), $level);
            $label = $prefix . Html::icon('folder-open') . basename($relativeFolder);
            Helper::addEntry($label, ['default/index', 'folder' => trim($relativeFolder, '/')]);
        }

        $mediaPath = $mediaRootPath . ($folder ? '/' . trim($folder, '/') : '');

        if (!is_dir($mediaPath)) {
            $mediaPath = Yii::getAlias($this->module->mediaPath);
        }
        $folders = FileHelper::findDirectories($mediaPath, ['recursive' => false]);
        $files = FileHelper::findFiles($mediaPath, ['recursive' => false]);
        sort($folders);
        sort($files);
        $media = array_merge($folders, $files);
        if ($folder) {
            array_unshift($media, 'uplevel');
        }

        return $this->render('index', ['media' => $media, 'upload' => $this->upload]);
    }

    /**
     * 删除文件或目录
     */
    public function actionDelete()
    {
        $folder = Yii::$app->request->get('folder');
        $check = Yii::$app->request->post('check');
        if (!is_array($check)) {
            $check = [$check];
        }
        if (empty($check)) {
            Yii::$app->session->setFlash('warning', Yii::t('mod_media', 'SELECTION_FROM_LIST'));
        }

        $mediaRootPath = Yii::getAlias($this->module->mediaPath);
        $session = Yii::$app->session;
        foreach ($check as $medium) {
            $mediumFile = $mediaRootPath . '/' . ($folder ? $folder . '/' : '') . $medium;
            if (file_exists($mediumFile)) {
                try {
                    if (is_dir($mediumFile)) {
                        FileHelper::removeDirectory($mediumFile);
                    } else {
                        FileHelper::unlink($mediumFile);
                    }
                    $session->addFlash('success', Yii::t('mod_media', 'DELETE_PROGRESS', $medium));
                } catch (\yii\base\ErrorException $e) {
                    $session->addFlash('error', $e->getMessage());
                }
            } else {
                $session->addFlash('error', Yii::t('mod_media', 'PATH_INVALID', $medium));
            }
        }

        $url = $folder ? ['index', 'folder' => $folder] : ['index'];
        $this->redirect($url);
    }

    /**
     * 创建目录
     */
    public function actionCreate()
    {
        $folder = Yii::$app->request->get('folder');
        $dirname = Yii::$app->request->post('dirname');

        $pattern = '/^[\w\-]+$/';
        if (preg_match($pattern, $dirname)) {
            $mediaRootPath = Yii::getAlias($this->module->mediaPath);
            $dirPath = $mediaRootPath . '/' . ($folder ? $folder . '/' : '') . $dirname;
            Yii::$app->session->setFlash('success', Yii::t('mod_media', 'DIRNAME_WRONGFUL'));
            if (mkdir($dirPath)) {
                Yii::$app->session->setFlash('success', Yii::t('mod_media', 'CREATE_DIR_SUCCESS', $dirname));
            } else {
                Yii::$app->session->setFlash('error', Yii::t('mod_media', 'CREATE_DIR_FAILED', $dirname));
            }
        } else {
            Yii::$app->session->setFlash('warning', Yii::t('mod_media', 'DIRNAME_WRONGFUL'));
        }


        $url = $folder ? ['index', 'folder' => $folder] : ['index'];
        $this->redirect($url);
    }

    /**
     * 上传文件
     */
    public function actionUpload()
    {
        $folder = Yii::$app->request->get('folder');
        $this->upload->file = UploadedFile::getInstance($this->upload, 'file');
        if ($this->upload->upload($this->module->mediaPath . ($folder ? '/' . $folder : ''))) {
            Yii::$app->session->addFlash('success', Yii::t('mod_media', 'UPLOAD_SUCCESS', $this->upload->file->name));
        } else {
            Yii::$app->session->addFlash('error', Helper::errorsToString($this->upload->errors));
        }
        $url = $folder ? ['index', 'folder' => $folder] : ['index'];
        $this->redirect($url);
    }
}
